// initial state
import {
  getGoodsInfo
} from "../../api/homegoodsdetail";
import {
  getMemberInfo
} from '../../api/member'

const state = {
  isOnline: false,
  token: null,
  info: null,
  point: {},
  inviterId: 0,
  isTokenInvalid: false,
  storeJoinin: {},
  openid: null
}

// mutations
const mutations = {
  sellerJoininSave(state, payload) {
    state.storeJoinin = Object.assign(
      state.storeJoinin,
      payload.storeJoinin)
  },
  memberInviterId(state, payload) {
    state.inviterId = payload.inviterId
  },
  memberPoint(state, payload) {
    state.point = Object.assign(
      state.point,
      payload.point)
  },
  memberToken(state, payload) {
    state.token = payload.token;
    // console.log(state.token)
  },
  clearToken(state, payload) {
    state.token = ''
  },
  memberLogin(state, payload) {
    state.info = payload.info
    state.info.invalid_time = parseInt((new Date().getTime()) / 1000) + 3600 // 一小时更新
    state.isOnline = true
    state.token = payload.token
    state.isTokenInvalid = false
  },
  memberLogout(state) {
    state.info = null
    state.isOnline = false
    state.token = null
  },
  memberUpdate(state, payload) {
    if (state.info) {
      state.info = payload.info
      state.info.invalid_time = parseInt((new Date().getTime()) / 1000) + 3600 // 一小时更新
    }
  },
  memberEdit(state, payload) {
    if (state.info) {
      let i
      for (i in payload) {
        state.info[i] = payload[i]
      }
    }
  },
  openIdUpdate(state, payload) {
    console.log('@'+payload)
    state.openid = payload.openid
  }
}

const actions = {
  // 获取商品详情
  getmemberinformation({
    commit,
    state
  }, params) {
    return new Promise((resolve, reject) => {
      // console.log(params.token);
      commit('memberToken', params);
      getMemberInfo().then(res => {
        commit('memberLogin', {
          token: params.token,
          info: res.result.member_info
        });
        resolve(res)
      }, (error) => {
        reject(error)
      })
    })
  }
}

export default {
  state,
  mutations,
  actions
}